package com.yihubang.taobaokotlin.presenter.impl

import com.yihubang.taobaokotlin.interfaces.IHomeCallback
import com.yihubang.taobaokotlin.model.Api
import com.yihubang.taobaokotlin.model.Categories
import com.yihubang.taobaokotlin.presenter.IHomePresenter
import com.yihubang.taobaokotlin.utils.RetrofitManage
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.HttpURLConnection

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/5/10.
 * PS: Not easy to write code, please indicate.
 */
object HomePresenterImpl : IHomePresenter {

    private var mCallback: IHomeCallback? = null

    override fun getCategories() {
        mCallback?.onLoading()
        //加载分类数据
        val retrofit = RetrofitManage.getRetrofit()
        val api = retrofit.create(Api::class.java)
        val categories = api.getCategories()
        categories.enqueue(object : Callback<Categories> {
            override fun onResponse(call: Call<Categories>, response: Response<Categories>) {
                //数据结果
                val code = response.code()
                if (code == HttpURLConnection.HTTP_OK) {
                    val body = response.body()
                    if (body?.data?.size == 0) {
                        mCallback?.onEmpty()
                    } else {
                        mCallback?.onCategoriesLoaded(body)
                    }
                } else {
                    //请求失败
                    mCallback?.onError()
                }
            }

            override fun onFailure(call: Call<Categories>, t: Throwable) {
                mCallback?.onError()
            }

        })
    }

    override fun registerViewCallback(callback: IHomeCallback) {
        mCallback = callback
    }

    override fun unregisterViewCallback(callback: IHomeCallback) {
        mCallback = null
    }

}